define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'eduadmin/classes/index',
                    add_url: 'eduadmin/classes/add',
                    edit_url: 'eduadmin/classes/edit',
                    del_url: 'eduadmin/classes/del',
                    multi_url: 'eduadmin/classes/multi',
                    enroll_url: 'eduadmin/enroll/classesgroup',
                    table: 'classes',
                }
            });

            var table = $("#table");

            			//定义操作
			function getFormatter (value, row, index, table) {
                //行操作
                var html = [];
                html.push('<a href="javascript:;" class="btn btn-info btn-student-view btn-xs" title="查看学员"><i class="fa fa-list"></i></a>');
            	html.push('<a href="javascript:;" class="btn btn-info btn-student-add btn-xs" title="添加学员"><i class="fa fa-plus-square"></i></a>');
                html.push('<a href="javascript:;" class="btn btn-xs btn-success btn-editone" title="编辑"><i class="fa fa-pencil"></i></a>');
                html.push('<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title="删除"><i class="fa fa-trash"></i></a>');
                return html.join(' ');
            }
			//定义事件
			var events = Table.api.events.operate;
            events['click .btn-student-view'] = function (e, value, row, index) {
                e.stopPropagation();
                var options = $(this).closest('table').bootstrapTable('getOptions');
                Backend.api.open(options.extend.enroll_url + "?classid=" + row[options.pk] + '&callback=delStudent', '已有学员');
            };
            events['click .btn-student-add'] = function (e, value, row, index) {
                e.stopPropagation();
                var options = $(this).closest('table').bootstrapTable('getOptions');
                Backend.api.open(options.extend.enroll_url + "?classid=" + row[options.pk] + '&callback=addStudent', '添加学员');
            };
            

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'createtime',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name')},
                        {field: 'branch_names', title: __('Branch')},
                        {field: 'course_name', title: __('Courseid')},
                        //{field: 'description', title: __('Description')},
                        {field: 'starttime', title: __('Starttime'), operate:'RANGE', addclass:'datetimerange', formatter: Controller.api.formatter.date},
                        {field: 'endtime', title: __('Endtime'), operate:'RANGE', addclass:'datetimerange', formatter: Controller.api.formatter.date},
                        {field: 'classcount', title: __('classcount')},
                        {field: 'classhour', title: __('classhour')},
                        {field: 'teacher_name', title: __('Teacher')},
                        {field: 'studentcount', title: __('studentcount')},
                        {field: 'enrollcount', title: __('enrollcount')},
                        //{field: 'createby', title: __('Createby')},
                        //{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        //{field: 'updateby', title: __('Updateby')},
                        {field: 'status', title: __('Status'), visible:false, searchList: {"\u5df2\u5173\u95ed":__('\u5df2\u5173\u95ed'),"\u5df2\u7ed3\u675f":__('\u5df2\u7ed3\u675f'),"\u5df2\u6682\u505c":__('\u5df2\u6682\u505c'),"\u672a\u5f00\u73ed":__('\u672a\u5f00\u73ed'),"\u5df2\u5f00\u73ed":__('\u5df2\u5f00\u73ed')}},
                        {field: 'status_text', title: __('Status'), operate:false},
                       // {field: 'weigh', title: __('Weigh')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                       // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                       {field: 'operate', title: __('Operate'), events: events, formatter: getFormatter}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
             //删除学员
            window.delStudent = function (classid, enrollid) {
                $.post('eduadmin/classes/delStudent',{
                    classid: classid,
            		enrollid:enrollid
            	},function(res){
            		if(res.code=='SUCCESS'){
            			layer.closeAll();
            			return Toastr.success(res.msg);
            		}else{
            			return Toastr.error(res.msg);
            		}
            	},'JSON');
            };
            //添加学员
            window.addStudent = function (classid, enrollid) {
                $.post('eduadmin/classes/addStudent',{
                    classid:classid,
                    enrollid:enrollid
                },function(res){
                    if(res.code=='SUCCESS'){
                        layer.closeAll();
                        return Toastr.success(res.msg);
                    }else{
                        return Toastr.error(res.msg);
                    }
                },'JSON');
            };
        },
        add: function () {
            Controller.api.bindevent();

            //选择器的初始化
            initSelectPage();
        },
        edit: function () {
            Controller.api.bindevent();

            //选择器的初始化
            initSelectPage();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                date: function (value, row, index) {
                    return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD") : __('None');
                }
            }
        }
    };

    //选择器的初始化
    function initSelectPage() {    
         //学校选择器的初始化
         var lastBranch = '';
         require(['selectpage'], function () {
             $('#c-branchids', $("form[role=form]")).selectPage({
                showField: 'name',
                keyField: 'id',
                data: 'branch/selectpage',
             eSelect: function (data) {
                     if(data && lastBranch !== data.id){
                         $('#c-courseid').selectPageClear();
                     }
             },
             eClear : function(){
                     $('#c-courseid').selectPageClear();
             }
             });
         });

         //课程选择器的初始化，使用空数据进行初始化
         require(['selectpage'], function () {
                 $('#c-courseid', $("form[role=form]")).selectPage({
                     showField: 'name',
                     keyField: 'id',
                     data: 'eduadmin/Course/selectpage',
                     //向服务端提交的参数中，增加已选中的
                     //设置返回-1，意为通知服务端返回空列表，初始化时使用
                     params: function(){
                         var pv = $('#c-branchids').val();
                         return {'custom[branchids]': pv?pv:'-1'};
                     }
             });
         });
    }
    return Controller;
});